
//
//  STComposeTextView.swift
//  STVVeibo
//
//  Created by leergou on 16/7/27.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit

class STComposeTextView: UITextView {
    
    //占位符
    var placeHolder: String?{
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    
    // 重写 font 属性,设置占位文本的字体大小与 textView 的字体大小一样
    override var font: UIFont? {
        didSet{
            placeHolderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 接收到textView 值改变调用的方法,监听方法
    func valueChanged(){
        placeHolderLabel.hidden = hasText()
    }
    
    //MARK: 设置视图
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        // 添加控件
        addSubview(placeHolderLabel)
        // 添加约束
        // 首先禁用自动约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
//        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -5))
        //MAKR- 第一次那样设置约束,不管用,宽度会超出屏幕,导致可以水平滚动,并且label 不会自动换行
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        
        // 通过系统通知,监听textView 的输入
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "valueChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    // MAKR: 移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: lazy
    private lazy var placeHolderLabel: UILabel = {
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textColor = UIColor.grayColor()
        return lab
    }()
    
    
}
